<?php

namespace App\Api\Controllers\Dong_Guan;

use EasyWeChat\Factory;
use Illuminate\Http\Request;

class OauthController extends BaseController
{
    private $wx_appid = 'wx4e41b2f311ded3b1';
    private $wx_secret = 'fa265a8e5e4569d1ad18f08ef71a7301';

    public function oauth(Request $request)
    {
        $json = $request->get('query');
        $data = json_decode(base64_decode((string)$json), true);
        $config = [
            'app_id' => $this->wx_appid,
            'scope' => 'snsapi_base',
            'oauth' => [
                'scopes' => ['snsapi_base'],
                'response_type' => 'code',
                'callback' => url('api/dong_guan/weixin/oauth_callback?query=' . $json),
            ],
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        return $oauth->redirect();
    }

    public function oauth_callback(Request $request)
    {
        $code = $request->get('code');
        $json = $request->get('query');
        $data = json_decode(base64_decode((string)$json), true);
        $config = [
            'app_id' => $this->wx_appid,
            "secret" => $this->wx_secret,
            "code" => $code,
            "grant_type" => "authorization_code",
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        $open_id = $user->getId();
        $data['open_id'] = $open_id;
        $json = base64_encode(json_encode((array)$data));
        return redirect('/api/dong_guan/weixin/pay_view?query=' . $json);
    }

    public function pay_view(Request $request)
    {
        $data = json_decode(base64_decode((string)$request->get('query')), true);
        return view('dong_guan.weixin', compact('data'));
    }

    public function un_pay(Request $request)
    {
        $data = json_decode(base64_decode((string)$request->get('query')), true);
        return view('dong_guan.un', compact('data'));
    }

}
